<?php
/**
 * Created by PhpStorm.
 * User: 郑合达
 * Date: 2019/3/12
 * Time: 20:41
 */

namespace app\app\controller;
use app\model\EquipmentModel;
use app\model\DeviceInfoModel;
use app\model\EnclosureModel;
class Map extends Common
{
    /**
     * @return \think\response\View
     * 定位页面
     */
    public function mapdata(){
        $data=EquipmentModel::where('equ_user',session('appuser.id'))->select()->toArray();
        if(input('imei')){
            $name=input('imei');
        }else if($data){
            $name =$data[0]['name'];
        }else{
            $name='';
        }
        session('dev_nik',$data);
        $this->assign('name',$name);
        $this->assign('data',$data);
        return view('mapdata');
    }
    //地图数据
    public function WebService(){
        $imei=input('imei');
        //判断是否绑定设备
        if($imei){
            //判断设备是否过期
            $extime =EquipmentModel::where('name',$imei)->value('expire_time');
            if($extime > time()){
                $data =DeviceInfoModel::where('imei',$imei)->find();
                //判断设备是否激活
                if($data){
                    $data->lastLocationsTime=date('Y-m-d H:i',$data->lastLocationsTime/1000);
                    $data->updateTime=date('Y-m-d H:i',$data->updateTime/1000);
                    return retJson($data,200,'数据返回成功');
                }
                return retJson($data,203,'设备未激活');
            }else{
                $data=[];
                return retJson($data,202,'设备已过期');
            }
        }else{
            $data=[];
            return retJson($data,201,'未绑定设备');
        }
//        //判断设备是否过期
//        $extime =EquipmentModel::where('name',$imei)->value('expire_time');
//        if($extime > time()){
//            $data =DeviceInfoModel::where('imei',$imei)->find();
//        }else{
//            $data=[];
//            return retJson($data,202,'设备已过期');
//        }
//        //没有定位数据
//        if($data){
//            $data->updateTime=date('Y-m-d H:i',$data->updateTime/1000);
//            return retJson($data,200,'数据返回成功');
//        }

    }
    //路径回放
    public function route(){
        $dev_nick =session('dev_nik');//用户昵称
        if($dev_nick){
            $name=$dev_nick[0]['name'];
            $imei1 =$dev_nick[0]['name'];
        }else{
            $name='';
            $imei1='';
        }
        if(input('imei')){
            $imei =input('imei');
            $time =input('gettime');
            $startTime = strtotime($time)*1000;//指点时间
            $endTime=$startTime+60*60*24*1000;
        }else{
            $imei=$imei1;
            $startTime =strtotime(date("Y-m-d"),time())*1000;//当前时间
            $endTime=$startTime+60*60*24;
        }
        $this->assign('name',$name);
        $this->assign('dev_nick',$dev_nick);
        //判断设备是否过期
        $extime =EquipmentModel::where('name',$imei)->value('expire_time');
        if($extime > time()){
            $list= $this->curl("http://api.huixun.me/open/device-path?token=4d9262b1a5da42779110baa9df648743&deviceImei=$imei&type=&startTime=$startTime&endTime=$endTime");
            $list=json_decode($list,true);

            if($list['data']){
                if ($list['code']==200){
                    foreach ($list['data'] as $k=>$v){
                        $bd_en= bd_encrypt($v['longitude'],$v['latitude']);//高德经纬度==转换==》百度经纬度
                        $time=$v['createTime']/1000;
                        $list['data'][$k]['createTime']=date('Y-m-d H:i',$time);
                        $list['data'][$k]['longitude']=$bd_en['bd_lon'];
                        $list['data'][$k]['latitude']=$bd_en['bd_lat'];

                    }
                }
            }else{
                $list['data']=[];
            }
        }else{
            $list['data']=[];

        }


//        dump($list['data']);die();
        $list=json_encode($list);

        $this->assign('list',$list);
        return view('lujing');
    }

    /**
     * @return \think\response\View
     * 显示围栏
     */
    public function fencead(){
        $res =EnclosureModel::where('user_id',session('appuser.id'))->select();
        $this->assign('res',$res);
        return view('fencead');
    }
    //添加电子栅栏
    public function fence(){
        return view('fence');
    }
    //高德实验接口
    public function gaode()
    {
//        header("content-type:text/html;charset=utf-8");
//        header('Content-Type:text/html;charset=utf-8');
//        $u='唐荣天润新城';
//        $u='alksszdcsa';
        //latitude  黄纬
        //longitude  黄经
        //$url="https://restapi.amap.com/v3/assistant/inputtips?key=99b02157ab12c170d0d395f81e7f41cf&keywords=%E6%B2%B3%E5%8C%97%E7%9C%81";
        $u=input('get.keywords');
        $key="5732c62d48ed0d67ca83e0ad6c98c461";
        $url="https://restapi.amap.com/v3/assistant/inputtips?key={$key}&keywords={$u}";
        $data=file_get_contents($url);
        $data=json_decode($data,true);
        $data['tips']=array_slice($data['tips'],0,5);
        if (count($data['tips'])>0){
            foreach ($data['tips'] as $k=>$v){
                if (isset($v['location'][0])){
                    $loca= explode(',',$v['location']);
                    $data['tips'][$k]['location']=$bd_encr=  bd_encrypt($loca[0],$loca[1]);
                }

            }
        }

        return $data;

    }
    //添加围栏功能
    public function enadd(){
        $data =input('post.');
        if(!$data['address']){
            return retJson('',201,'该地区不能设置围栏');
        }
        $data['user_id'] = session('appuser.id');
        $res =EnclosureModel::create($data);
        if($res){
            return retJson('',200,'设置成功');
        }
        return retJson('',201,'设置失败');
    }

    /**
     * 是否启用围栏
     */
    public function fenedit(){
        $data =input('post.');
        $arr=[];
        $arr['id'] = $data['id'];
        $arr['state'] = $data['state'];
        if($data['state'] ==1){
            $data['state']=2;
        }else {
            $data['state']=1;
        }
        $res =EnclosureModel::update($data);
        if($res){
            return retJson($arr,200,'成功');
        }
        return retJson('',201,'失败');
    }
    /**
     * 删除围栏
     */
    public function det(){
        $data =input('post.');
        $res =EnclosureModel::destroy($data);
        if($res){
            return retJson('',200,'删除成功');
        }
        return retJson('',201,'删除失败');
    }
//查询地址
    public function  address(){
        $lat=input('lat');
        $lng=input('lng');
        $ok=[];
        $list= $this->curl("http://api.map.baidu.com/geocoder/v2/?ak=D4bef01281a3d8dcea3f4db5cda88522&location=$lat,$lng&callback=renderReverse&output=json&pois=0");
//          $list1= $this->curl("http://api.map.baidu.com/geocoder/v2/?address=河北省北斗导航位置服务有限公司&output=json&ak=D4bef01281a3d8dcea3f4db5cda88522&callback=showLocation");

//          dump($list1);die();
        preg_match_all("/(?:\()(.*)(?:\))/i",$list, $ok);
        $data=json_decode($ok[1][0],true);
        if($data){
            return retJson($data["result"]["sematic_description"],200,'成功');
        }
        return retJson($data["result"]["sematic_description"],201,'失败');
    }

    /**
     * @param $url   接口连接的地址
     * @return mixed
     *  转接接口的方法
     */
    public function curl($url){
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        $data=json_decode($output,true);//$data就是最终的数据 而且已经转换成了数组
        return $output;
    }
    /* 毫秒时间戳转换成日期 */
    public function msecdate($time)
    {
        $tag='Y-m-d H:i:s';
        $a = substr($time,0,10);
        $b = substr($time,10);
        $date = date($tag,$a).'.'.$b;
        return $date;
    }


    /*
     * 常开页面
     */
    public function ssss_index()
    {
        return view();
    }
}